<template>
  <a-card class="general-card" title="计量单位" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary"  @click="handleAdd">
            添加
          </a-button>
          <a-button @click="delAll"> 批量删除 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <PickTablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getUnitList"
      :checkbox="true"
      @delete="handleDelete"
      @editor="handleEdit"
      @selectTableChange="selectTableChange"
      :bordered="true"
    >
    </PickTablePage>
    <!-- 添加/编辑modal -->
    <a-modal
      v-model:visible="unitData.enableAddModal"
      :align-center="false"
      :footer="false"
    >
      <template #title> {{ title }} </template>
      <a-form ref="formRef" :model="unitData.form" @submit="handleAddOk">
        <a-form-item
          field="name"
          label="计量单位"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="unitData.form.name" />
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="unitData.formLoading" html-type="submit"
          type="primary" >保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import { PickTablePage } from '@pickmall/ui-v3-components'  
  import { MethodsRule, ColumnsDataRule } from '@/types/global';
  import {
    getUnitList,
    delGoodsUnit,
    addGoodsUnit,
    updateGoodsUnit,
  } from '@/api/goods';
  import { ref, reactive } from 'vue';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';

  const selectList = ref([]); // 接收子组件传过来的值
  const tablePageRef = ref<any>();
  const title = ref<string>('');
  const ids = ref<string>(''); // 多选行id
  const formRef = ref<FormInstance>();
  interface formInterface {
    enableAddModal: boolean;
    formLoading: boolean;
    fid: string | number;
    form: {
      name: string;
      [key:string]: any;
    };
    [key:string]: any;
  }
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const columnsTable: ColumnsDataRule[] = [
    {
      title: '计量单位',
      dataIndex: 'name',
      width: 150,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 150,
    },
    {
      title: '操作人',
      dataIndex: 'createBy',
      width: 150,
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 250,
    fixed: 'right',
    methods: [
      {
        title: '修改',
        callback: 'editor',
        type:"text" ,
        status:"warning"
      },

      {
        title: '删除',
        callback: 'delete',
        type:"text" ,
        status:"danger"
      },
    ],
  };
  // 数据集
  const unitData = reactive<formInterface>({
    enableAddModal: false,
    formLoading: false,
    fid: '', // 当前form的ids
    form: {
      name: '',
    }, // 表单提交数据
  });
  // 选择的行
  const selectTableChange = (val: any) => {
    selectList.value = val;
  };
  // 点击添加
  function handleAdd() {
    unitData.enableAddModal = true;
    title.value = '添加';
    unitData.fid = '';
    Object.keys(unitData.form).forEach((key) => {
      unitData.form[key] = '';
    });
  }
  // 添加/修改地址
  async function handleAddOk() {
    // unitData.form.password = this.md5(unitData.form.password);
    const auth = await formRef.value?.validate();
    if (!auth) {
      let res;
      !unitData.fid
        ? (res = await addGoodsUnit(unitData.form))
        : (res = await updateGoodsUnit(unitData.fid, unitData.form));

      if (res.data.success) {
        Message.success(`${unitData.fid ? '修改' : '添加'}成功!`);
        unitData.enableAddModal = false;
        tablePageRef.value.init();
      }
    }
  }
  // 点击修改地址
  function handleEdit(val: any) {
    title.value = '编辑';
    if (val) {
      Object.keys(val.record).forEach((key) => {
        // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
        unitData.form.hasOwnProperty(key)
          ? (unitData.form[key] = val.record[key])
          : '';
      });
      unitData.fid = val.record.id;
      unitData.enableAddModal = true;
    }
  }
  // 回调删除
  function handleDelete(data: any) {
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除${data.record.name}?`,
      alignCenter: false,
      onOk: async () => {
        const res = await delGoodsUnit(data.record.id);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  }
  // 批量删除
  const delAll = () => {
    if (selectList.value.length <= 0) {
      Message.error('您还未选择要删除的数据');
      return;
    }
    selectList.value.forEach((item: any) => {
      ids.value += `${item.id},`;
    });
    const joinid = ids.value.substring(0, ids.value.length - 1);
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除所选的${selectList.value.length}条数据?`,
      alignCenter: false,
      onOk: async () => {
        const res = await delGoodsUnit(joinid);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  };
</script>

<script lang="ts">
  // eslint-disable-next-line import/export
  // export default {
  //   name: 'GoodsList',
  // };
</script>
